package HASH;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class item17
{

    public static List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
        return combinations;
    }
    //        经典的回溯算法，相当于对三叉树进行遍历
    public static void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {

//        如果k>n 那么<x1,x2,x3....xn>为解，在本题中如果一个枝干上上遍历完了就加入到list中，也就是index等于str的长度的时候
        if (index == digits.length()) {
            combinations.add(combination.toString());
            return;
        } else {
//            否则，进行深度优先遍历
            char digit = digits.charAt(index);//比如说是'2'
            String letters = phoneMap.get(digit);//得到“abc”
            int lettersCount = letters.length();
            for (int i = 0; i < lettersCount; i++) {
                combination.append(letters.charAt(i)); //先得到a
                backtrack(combinations, phoneMap, digits, index + 1, combination);//继续深度优先遍历

                combination.deleteCharAt(index);//当到叶子节点的时候去除buffer里面的内容,上一步完成之后会自动回到父节点，也就是当index = 2时满足判断条件结束，回到index=1的地方，
            }
        }
    }

    public static void main(String[] args) {
        String str = "23";
        List list = letterCombinations(str);
        System.out.println(list);
    }
}
